package com.example.environment.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.environment.pojo.Staff;
import com.example.environment.pojo.Supervisor;
import com.example.environment.tools.JwtUtil;
import com.example.environment.tools.common.ResultMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class AuthService {
    @Autowired
    private StaffService staffService;

    @Autowired
    private SupervisorService supervisorService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public ResultMsg staffLogin(String id, String password){
        // 假设有一个 QueryWrapper 对象，设置查询条件，并且不抛出异常
        QueryWrapper<Staff> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("password", password);
        queryWrapper.eq("id", id);
        Staff AccStaff = staffService.getOne(queryWrapper, false); // 调用 getOne 方法
        if (AccStaff != null) {
            System.out.println("Staff found: " + AccStaff.getId());
            String token = JwtUtil.generateToken(AccStaff.getId().toString());
            assert token != null;
            redisTemplate.opsForValue().set(token, id, 1, TimeUnit.HOURS);
            return ResultMsg.successOp(token);
        } else {
            System.out.println("Staff not found.");
            return ResultMsg.failOp("登录失败");
        }
    }
    public ResultMsg SvLogin(String phone, String password){
        // 假设有一个 QueryWrapper 对象，设置查询条件，并且不抛出异常
        QueryWrapper<Supervisor> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("password", password);
        queryWrapper.eq("phone", phone);
        Supervisor supervisor = supervisorService.getOne(queryWrapper, false); // 调用 getOne 方法
        if (supervisor != null) {
            System.out.println("Supervisor found: " + supervisor.getId());
            String token = JwtUtil.generateToken(supervisor.getId());
            assert token != null;
            redisTemplate.opsForValue().set(token, phone, 1, TimeUnit.HOURS);
            return ResultMsg.successOp(token);
        } else {
            System.out.println("Supervisor not found.");
            return ResultMsg.failOp("登录失败");
        }
    }

    public ResultMsg validate(String token){
        if (JwtUtil.getStaffId(token)==null) {
            return ResultMsg.failOp("无效token");
        }
        System.out.println("22");
        // 验证 token 是否存在于 Redis 中
        String username = (String) redisTemplate.opsForValue().get(token);
        System.out.println("33");
        if(username!=null){
            System.out.println("4");
            return ResultMsg.successOp(username);
        }
        System.out.println("55");
        return ResultMsg.failOp("未登陆");
    }


}
